﻿using HamcoWcs.Tools.LogCleaner.Entities;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace HamcoWcs.Tools.LogCleaner
{
    internal partial class Program
    {
        private static int DEFAULT_LOG_SAVE_DAY = 90;

        static void Main(string[] args)
        {
            //MonitorMainProcess();
            //SQLCLIENT.DbFirst.IsCreateAttribute().CreateClassFile("D:\\Demo\\1", "Models");
            try
            {
                int logSaveDay = GetLogSaveDay();
                DateTime dateThreshold = DateTime.Now.AddDays(0 - logSaveDay);
                DeleteDeviceErrorLog(dateThreshold);
                DeleteOperationLog(dateThreshold);
                DeleteWcsRunLog(dateThreshold);
                DeleteSystemErrorLog(dateThreshold);
                DeleteMesMsgQueueBak();
                //DeleteTask(dateThreshold);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


            PRESS_KEY_QUIT();
        }


        private static int GetLogSaveDay()
        {
            var logSaveDayConfig = SQLCLIENT.Queryable<BaseConfig>().Where(x => x.ConfigKey == "LOGDELETEEXPIRED").First();

            int logSaveDay = logSaveDayConfig != null ? (int.TryParse(logSaveDayConfig.ConfigValue, out int t) ? t : DEFAULT_LOG_SAVE_DAY) : DEFAULT_LOG_SAVE_DAY;

            if (logSaveDay > DEFAULT_LOG_SAVE_DAY) logSaveDay = DEFAULT_LOG_SAVE_DAY;

            return logSaveDay;
        }


        /// <summary>监控主程序进程</summary>
        static void MonitorMainProcess()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    var progress = Process.GetProcessesByName("HamcoWcs.Main");

                    if (progress.Length == 0)
                    {
                        Console.WriteLine($"LogCleaner Server:[WARNING],WCS main process is shutdown,TibcoExchange will auto close.");

                        try
                        {
                            SQLCLIENT.Insertable<SystemErrorLog>(new SystemErrorLog()
                            {
                                Log = $"LogCleaner Server:[WARNING],WCS main process is shutdown,TibcoExchange will auto close.",
                                CreatedTime = DateTime.Now,
                            }).ExecuteCommand();
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("log error");
                        }
                        finally
                        {
                            Process.GetCurrentProcess().Kill();
                        }

                    }
                    Thread.Sleep(1000);
                }
            });
        }

        /// <summary>按ESC键退出</summary>
        private static Action PRESS_KEY_QUIT = () =>
        {
            var key = Console.ReadKey();

            while (key.Key != ConsoleKey.Escape)
            {
                key = Console.ReadKey();
            }
        };

        private static ISqlSugarClient GetSqlSugarClient() => new SqlSugarScope(new ConnectionConfig()
        {
            DbType = DbType.MySql,
            IsAutoCloseConnection = true,
            InitKeyType = InitKeyType.Attribute,
            ConnectionString = Configuration["ConnectionStrings:MysqlString"],
        });
        public static IConfiguration Configuration { get; set; }
        public static ISqlSugarClient SQLCLIENT { get; set; }

        static Program()
        {
            Console.Title = "LogCleaner";
            IConfigurationBuilder cfgBuilder = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json");
            Configuration = cfgBuilder.Build();

            SQLCLIENT = GetSqlSugarClient();
        }
    }
}
